class_name FuWuQIGuangBo
extends Node

# -------------------------- 配置参数 --------------------------
@export var broadcast_port_start: int = 7730   # 广播UDP端口起始搜索点
@export var broadcast_interval: float =0.2
@export var server_name: String = "My Game Server"

# -------------------------- 私有变量 --------------------------
var udp_broadcaster: PacketPeerUDP
var broadcast_timer: Timer
var is_broadcasting: bool = false
var current_broadcast_port: int = 7730
var current_game_tcp_port: int = -1

# -------------------------- 公共接口 --------------------------
# 启动广播（由父级调用，传入要广播的TCP端口）
func start_broadcasting(tcp_port: int) -> void:
	if current_game_tcp_port > 0:
		print("广播器已在运行，端口: ", current_game_tcp_port)
		return
	
	if tcp_port <= 0:
		push_error("无效的TCP端口: " + str(tcp_port))
		return
	
	current_game_tcp_port = tcp_port
	_initialize_broadcaster()

# 停止广播
func stop_broadcasting() -> void:
	if not is_broadcasting:
		return
		
	_stop_broadcasting()
	udp_broadcaster=null
# -------------------------- 内部实现 --------------------------
# 初始化广播器
func _initialize_broadcaster() -> void:
	print("=== 初始化广播器 ===")
	
	# 创建UDP广播器
	udp_broadcaster = PacketPeerUDP.new()
	
	# 创建广播定时器
	broadcast_timer = Timer.new()
	broadcast_timer.wait_time = broadcast_interval
	broadcast_timer.one_shot = false
	broadcast_timer.timeout.connect(_on_broadcast_timer_timeout)
	add_child(broadcast_timer)
	
	# 启动广播
	_start_broadcasting()

# 内部启动广播
func _start_broadcasting() -> void:
	print("=== 启动服务器广播 ===")
	
	# 寻找可用的UDP广播端口
	current_broadcast_port = broadcast_port_start
	while _is_udp_port_in_use(current_broadcast_port) and current_broadcast_port < 65535:
		current_broadcast_port += 1
	
	if current_broadcast_port >= 65535:
		push_error("无法找到可用的UDP广播端口")
		return
	
	print("UDP广播端口: ", current_broadcast_port)
	
	# 初始化UDP广播
	udp_broadcaster.set_broadcast_enabled(true)
	var bind_result = udp_broadcaster.bind(current_broadcast_port)
	if bind_result != OK:
		push_error("无法绑定到UDP端口 " + str(current_broadcast_port))
		return
	
	# 启动定时器
	is_broadcasting = true
	broadcast_timer.start()
	
	print("✅ 广播已启动 -> UDP:", current_broadcast_port, " TCP:", current_game_tcp_port)

# 内部停止广播
func _stop_broadcasting() -> void:
	print("=== 停止服务器广播 ===")
	
	# 停止定时器
	if broadcast_timer:
		broadcast_timer.stop()
	
	is_broadcasting = false
	
	# 关闭socket
	if udp_broadcaster and udp_broadcaster.is_socket_connected():
		udp_broadcaster.close()
	
	# 清理定时器
	if broadcast_timer and broadcast_timer.get_parent():
		remove_child(broadcast_timer)
		broadcast_timer.queue_free()
		broadcast_timer = null
	
	current_game_tcp_port = -1
	print("广播已停止")

# -------------------------- 端口检测 --------------------------
func _is_udp_port_in_use(port: int) -> bool:
	var socket = PacketPeerUDP.new()
	var err = socket.bind(port)
	if err == OK:
		socket.close()
		return false
	else:
		return true

# -------------------------- 广播逻辑 --------------------------
func _on_broadcast_timer_timeout() -> void:
	if not is_broadcasting or current_game_tcp_port <= 0:
		return
	udp_broadcaster.set_broadcast_enabled(true)
	udp_broadcaster.set_dest_address("255.255.255.255", broadcast_port_start)	
	var server_ips: Array = []
	var ips = IP.get_local_addresses()

	# 收集局域网IPv4
	for ip in ips:
		if ":" not in ip and ip.begins_with("192.168."):
			server_ips.append(ip)

	if server_ips.is_empty():
		return
	print("udp端口"+str(broadcast_port_start))
	# 广播服务器信息
	for server_ip in server_ips:
		var server_info = {
			"name": server_name,
			"ip": server_ip,
			"tcp_port": current_game_tcp_port,
		}

		var json_string = JSON.stringify(server_info)
		var data = json_string.to_utf8_buffer()
		print("ip"+str(server_ip)+str(current_game_tcp_port))
		udp_broadcaster.put_packet(data)

# -------------------------- 资源释放 --------------------------
func _exit_tree() -> void:
	_stop_broadcasting()
